package com.gict.antifraudback.controller.front.article;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gict.antifraudback.entity.LikeRecord;
import com.gict.antifraudback.exception.BusinessException;
import com.gict.antifraudback.result.ResultView;
import com.gict.antifraudback.service.LikeRecordService;
import com.gict.antifraudback.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.sql.Wrapper;
import java.util.Map;

/**
 * @author ThinkPad
 */
@RestController
@Slf4j
@RequestMapping("/mapi/likeRecord")
public class FrontLikeRecordController {

    @Autowired
    private LikeRecordService likeRecordService;

    /**
     * 取消点赞
     * @param map
     * @return
     */
    @PostMapping("/noLike")
    public ResultView delete(@RequestBody Map<String, Object> map) {
        Object id = map.get("id"); // 文章id或评论id
        if (id == null) {
            throw new BusinessException("id is null");
        }
        Object type = map.get("type"); // 'article', 'comment'
        if (type == null) {
            throw new BusinessException("type is null");
        }
        LambdaQueryWrapper<LikeRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(LikeRecord::getUserId, UserThreadLocal.get().getId());
        wrapper.eq(LikeRecord::getTargetType, type);
        wrapper.eq(LikeRecord::getTargetId, id);
        likeRecordService.remove(wrapper);
        return ResultView.okMsg("删除成功");
    }

    /**
     * 点赞
     * @param likeRecord
     */
    @PostMapping("/like")
    public ResultView add(@Valid @RequestBody LikeRecord likeRecord) {
        likeRecord.setUserId(UserThreadLocal.get().getId());
        likeRecordService.save(likeRecord);
        return ResultView.ok();
    }

    /**
     * 获取点赞数量
     * @param id 文章id
     * @param type 类型 article comment
     */
    @GetMapping("/getLikeCount")
    public ResultView getLikeCount(@Valid @NotNull Integer id, @Valid @NotNull String type) {
        likeRecordService.count(Wrappers.<LikeRecord>lambdaQuery().eq(LikeRecord::getTargetType, type).eq(LikeRecord::getLikeType, 0).eq(LikeRecord::getTargetId, id));
        return ResultView.ok();
    }

}
